package com.albon.alarm;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import com.albon.sportsalarm.R;


import android.app.Activity;
import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;

public class MusicRingtone extends Activity {
   private String TAG = "MusicRingtone";
	private ListView listView = null;
	Button ok = null;
	Button cancel = null;
	List<String> artists;
	ArrayAdapter<String> arrayAdater;
	
	private MediaPlayer mMediaPlayer;
	private AudioManager mAudioManager;
	private int resetVolume;
	private String requestCode = "";
	public HashMap<Integer, String> music_uri = new HashMap<Integer, String>();
	private String music_tone = "";
	private int position_value = -1;
	private final String[] INTERNAL_COLUMNS = new String[] {
			android.provider.BaseColumns._ID,
			android.provider.MediaStore.MediaColumns.TITLE,
			"\"" + MediaStore.Audio.Media.INTERNAL_CONTENT_URI + "\"",
			android.provider.MediaStore.Audio.AudioColumns.TITLE_KEY  
		};
		private final String[] EXTERNAL_COLUMNS = new String[] {
	   	     android.provider.BaseColumns._ID, 
	   	     android.provider.MediaStore.MediaColumns.TITLE,
	   	     "\"" + MediaStore.Audio.Media.EXTERNAL_CONTENT_URI + "\"",
	   	     android.provider.MediaStore.Audio.AudioColumns.TITLE_KEY
		};
		private ContentResolver resolver;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		music_tone = getIntent().getStringExtra("music_tone");
		Log.d(TAG, "music_tone : "+music_tone);
		setContentView(R.layout.music_ringtone_list);
		 resolver = getContentResolver(); 
		mAudioManager = (AudioManager)getSystemService(Context.AUDIO_SERVICE);
		resetVolume = mAudioManager.getStreamVolume(AudioManager.STREAM_ALARM);
		
		 artists = getArtists();  
		 arrayAdater = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_single_choice, artists);
		 listView = (ListView)findViewById(R.id.ringtone_mp3_type);
         listView.setAdapter(arrayAdater);
         if(music_tone!=null && !music_tone.equals("")){
        	 Log.d(TAG, "music_tone : "+music_tone);
           rington_uri(music_tone);
         }
         if(position_value != -1){
        	 Log.d(TAG, "position_value1 : "+position_value);
        	 listView.setItemChecked(position_value, true);
         }
         Log.d(TAG, "position_value2 : "+position_value);
         listView.setOnItemClickListener(musicOnItemClickListener);
         
         ok = (Button)findViewById(R.id.okBtn);
 	    ok.setOnClickListener(new OnClickListener() {
 			
 			@Override
 			public void onClick(View v) {
 				// TODO Auto-generated method stub
 				Intent intent = getIntent();
 				//Log.d(TAG, "requestCode : "+requestCode);
 				//Log.d(TAG, "music_tone : "+music_tone);
 				if((music_tone!=null &&!music_tone.equals("")) && requestCode.equals("")){
 					requestCode = music_tone;
 				}
 				intent.putExtra("music_alarm", requestCode);
 				setResult(RESULT_OK, intent);
 				releaseAlarm();
 				finish();
 				
 			}
 		});
 	    cancel = (Button)findViewById(R.id.cancelBtn);
 	    cancel.setOnClickListener(new OnClickListener() {
 	    	
 	    	@Override
 	    	public void onClick(View v) {
 	    		// TODO Auto-generated method stub
 	    		//mVib.cancel();
 	    		releaseAlarm();
 	    		finish();
 	    	}
 	    });
		
	}
	
	public List<String> getArtists() {  
		        List<String> list = new ArrayList<String>();  
		        String[] cursorColumns = new String[] {  
		        		MediaStore.Audio.Media._ID,
		                MediaStore.Audio.Media.TITLE,
		               MediaStore.Audio.Media.ARTIST,
		               MediaStore.Audio.Media.DURATION
		        };  
		        Cursor cursor = (Cursor) getContentResolver().query(  
		        		MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,  
		               cursorColumns, null, null, null);  
	          
		       if (cursor == null) {  
		            return list;  
		       }  
		       if (cursor.moveToFirst()) {  
		            int idColumn = cursor.getColumnIndex(MediaStore.Audio.Media._ID);  
		           
		          int musicTitleColumn = cursor.getColumnIndex(MediaStore.Audio.Media.TITLE);  
		          int i = 0; 
		          do  
		          {  
		        	    music_uri.put(i, cursor.getString(idColumn));
		                String artist = cursor.getString(musicTitleColumn);  
		                //Log.d(TAG, "idColumn : "+(cursor.getString(idColumn)+" i : "+i));
		                list.add(artist); 
		                i++;
		                
		                
		            } while (cursor.moveToNext());  
		       }  
		        cursor.close();  
		       return list;  
		   }  

	
	
	AdapterView.OnItemClickListener musicOnItemClickListener = new AdapterView.OnItemClickListener() {

		@Override
		public void onItemClick(AdapterView<?> parent, View view, int position,
				long id) {
			// TODO Auto-generated method stub
			
//			Log.d(TAG, "position : "+"content://media/"+MediaStore.Audio.Media.EXTERNAL_CONTENT_URI + "/" +(music_uri.get(position)));
//			Log.d(TAG, "position : "+MediaStore.Audio.Media.EXTERNAL_CONTENT_URI + "/" +(music_uri.get(position)));
			
			
			playMusic(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI + "/" +(music_uri.get(position)));
			requestCode = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI + "/" +(music_uri.get(position));
		}
	};
	
	
	@Override
	protected void onUserLeaveHint() {
		// TODO Auto-generated method stub
		super.onUserLeaveHint();
		Log.e(TAG,"===KEYCODE_HOMEKEY===");
		releaseAlarm();
	}
	
	@Override
	public boolean onKeyUp(int keyCode, KeyEvent event) {
		boolean check = true;
		//Log.e(TAG,"keyCode = "+keyCode+" //// event = "+event);
		switch(keyCode)
		{
		case KeyEvent.KEYCODE_BACK : 
			Log.e(TAG,"===KEYCODE_BACK===");
			releaseAlarm();
			break;
		}
		return super.onKeyUp(keyCode, event);
	}
	
	 void rington_uri(String ringtone){
	    	Log.d(TAG, "ringtone : "+ringtone);
//	    	Cursor ring = null;
//	    	boolean find_ringtone = false;
	    	
//	    	try {
//				ring = resolver.query(MediaStore.Audio.Media.INTERNAL_CONTENT_URI, INTERNAL_COLUMNS, "", null, MediaStore.Audio.Media.DEFAULT_SORT_ORDER);
//				if(ring != null && ring.moveToFirst()){
//					//mAlarmtoneSub.setText(getText(R.string.silent_alarm_summary).toString());
//					do{
//						Uri uri1 = ContentUris.withAppendedId(Uri.parse(ring.getString(2)), ring.getLong(0));
//						Log.e(TAG, "uri1 = " + uri1.toString());
//						Log.d(TAG, "ring = " + ringtone);
//						int ii = 0;
//						if(uri1.toString().equalsIgnoreCase(ringtone)){
//							//mAlarmtoneSub.setText(ring.getString(1));
//							//Log.d(TAG,"ring.getString(1) : "+ring.getColumnIndex(ring.getString(1)));
//							position_value = ii;
//							Log.e(TAG, "e //: ");
//							find_ringtone = true;
//							break;
//						}
//						ii++;
//					}while(ring.moveToNext());
//					
//				}
//					if(!find_ringtone){
//						Log.d(TAG,"find_ringtone : "+find_ringtone);
						Cursor cur = null;
						try {
							cur = resolver.query(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, EXTERNAL_COLUMNS, "", null, "_id");
//							if(cur == null){
								
								//Log.d(TAG, "cur == null");		
								//ringtone_uri = "Off";
								//mAlarmtoneSub.setText(getText(R.string.silent_alarm_summary).toString());
//							}else{
								if (cur != null && cur.moveToFirst() ) {
									int iii = 0;
									do {	
									//	Log.d(TAG, "cur != null");		
										Uri uri1 = ContentUris.withAppendedId(Uri.parse(cur.getString(2)), cur.getLong(0));
										if ( uri1.toString().equalsIgnoreCase(ringtone) ) {
//											Log.e(TAG, "cur.getString(1) : "+cur.getString(1));
											//mAlarmtoneSub.setText(cur.getString(1));
											Log.d(TAG,"ring.getString(q) : "+cur.getColumnIndex(MediaStore.Audio.Media._ID));
											position_value = iii;
											break;
										}
										iii++;
									}while(cur.moveToNext());
								}
//							}
						}catch (Exception e) {
							// TODO: handle exception
							Log.e(TAG, "e //: "+e);
						}finally{
							if(cur!=null){
								cur.close();
							}
						}
//					}
//			} catch (Exception e) {
//				// TODO: handle exception
//			}finally{
//				if(ring!=null){
//					ring.close();
//				}
//			}
	    }
	
/*---------------------------------------music play-----------------------------------------------------*/	
    private int nMax;
	public void playMusic(String ringtone) {
		releaseWaitAlarm();
		nMax = mAudioManager.getStreamMaxVolume(AudioManager.STREAM_ALARM);
			 mAudioManager.setStreamVolume(AudioManager.STREAM_ALARM, nMax, 0);
				mMediaPlayer = new MediaPlayer();	
		
		try {	
	         mMediaPlayer.setDataSource(this, Uri.parse(ringtone));
	            
	            if ( mMediaPlayer != null ) {
	            	mMediaPlayer.setAudioStreamType(AudioManager.STREAM_ALARM);
			    	mMediaPlayer.setLooping(true);
			    	mMediaPlayer.setVolume(mAudioManager.getStreamVolume(AudioManager.STREAM_RING), mAudioManager.getStreamVolume(AudioManager.STREAM_RING));
					mMediaPlayer.prepare();
	            }
			
		}
		catch (IllegalArgumentException e1) { 
			Log.e(TAG, "e1 : "+e1);
		} 
		catch (SecurityException e2) {
			Log.e(TAG, "e1 : "+e2);
		}
		catch (IllegalStateException e3) {
			Log.e(TAG, "e1 : "+e3);
		}
		catch (IOException e4) {
			Log.e(TAG, "e1 : "+e4);
			
		}
		
		if ( mMediaPlayer != null )
			mMediaPlayer.start();
	}
	
	
	private void releaseWaitAlarm() {
		
		if (mMediaPlayer != null) {
			mMediaPlayer.stop();
			mMediaPlayer.release();
			
		}
	}	
	private void releaseAlarm() {
	
		if (mMediaPlayer != null) {
			mMediaPlayer.stop();
			mMediaPlayer.release();
			mMediaPlayer = null;
          
		}
	}	
}
